package com.hyts.reactor.handler.subcribe;

import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;

import java.util.function.Function;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.reactor.handler.subcribe
 * author:Libo/Alex
 * create-date:2019-06-25 15:42
 * email:liboware@gmail.com
 * description:此类主要用于: map映射订阅关系构建器
 */
@RequiredArgsConstructor
public class MapSubscription<T, R> implements Subscriber<T>, Subscription{


    private final Subscriber<? super R> actual;

    private final Function<? super T, ? extends R> mapper;

    boolean done;

    Subscription subscriptionOfUpstream;


    @Override
    public void onSubscribe(Subscription s) {
        this.subscriptionOfUpstream = s;
        actual.onSubscribe(this);
    }

    @Override
    public void onNext(T t) {
        if (done) {
            return;
        }
        actual.onNext(mapper.apply(t));
    }

    @Override
    public void onError(Throwable t) {
        if (done) {
            return;
        }
        done = true;
        actual.onError(t);
    }

    @Override
    public void onComplete() {
        if (done) {
            return;
        }
        done = true;
        actual.onComplete();
    }

    @Override
    public void request(long n) {
        this.subscriptionOfUpstream.request(n);
    }

    @Override
    public void cancel() {
        this.subscriptionOfUpstream.cancel();
    }
}
